package main

import (
	"context"
	"elflog/common/config"
	context2 "elflog/common/context"
	"elflog/common/dig"
	"elflog/component/cron"
	"elflog/component/ndb"
	"elflog/component/nlog"
	service2 "elflog/module/module-account/service"
	"elflog/module/module-log/service"
	"elflog/server/httpapi"
	controller_logger "elflog/server/httpapi/controller-logger"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	dig.Container.MustInvoke(func(cornJob *cron.NCron, cfg *config.Config, db *ndb.NDb, log *nlog.NLog, logCtrl *controller_logger.ControllerLogger, moduleLog *service.ModuleLogService, moduleAccount *service2.ModuleAccountService) {
		ctx := context2.NewContext()
		moduleAccount.InitData(ctx)                             // 数据初始化
		exitApi := httpapi.StartHttpApi(ctx, log, cfg, logCtrl) // 开始http服务
		WaitSignalAndExit(ctx, func() {
			err := exitApi(time.Second * 10) // http 服务
			if err != nil {
				log.Error(err)
			}
			moduleLog.StopSaveWorker(ctx) // 保存日志的队列
			cornJob.StopAndWait(ctx)      // 定时任务
			db.CloseDb()                  // 数据库
			log.Info("server down success...")
		})
	})
}

// 接收信号和退出
func WaitSignalAndExit(ctx context.Context, exit func()) {
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL)
	for {
		s := <-c
		switch s {
		case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL:
			exit()
			return
		case syscall.SIGHUP:
		default:
			return
		}
	}
}
